"""
应用配置设置
使用pydantic-settings管理环境变量配置
"""

import logging
from typing import List, Optional, Dict, Any
from pydantic_settings import BaseSettings
from pydantic import Field, field_validator, model_validator
from pydantic_settings import SettingsConfigDict
import os
import json
import yaml
import copy
from dotenv import load_dotenv
from datetime import datetime
import hashlib

# 创建logger实例
logger = logging.getLogger(__name__)

load_dotenv()


class DatabaseSettings(BaseSettings):
    """数据库配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="DATABASE_"
    )
    
    URL: str = Field(
        default="sqlite:///./tickets.db",
        description="数据库连接URL"
    )
    POOL_SIZE: int = Field(
        default=5,
        description="数据库连接池大小",
        ge=1,
        le=100
    )
    MAX_OVERFLOW: int = Field(
        default=10,
        description="数据库连接池最大溢出数",
        ge=0,
        le=100
    )
    POOL_TIMEOUT: int = Field(
        default=30,
        description="数据库连接池超时时间(秒)",
        ge=1,
        le=300
    )
    POOL_RECYCLE: int = Field(
        default=1800,
        description="数据库连接回收时间(秒)",
        ge=0,
        le=7200
    )
    ECHO: bool = Field(
        default=False,
        description="是否输出SQL日志"
    )
    
    @model_validator(mode='after')
    def validate_database_settings(self) -> 'DatabaseSettings':
        """验证数据库配置"""
        if not self.URL:
            raise ValueError("数据库URL不能为空")
        return self


class JWTSettings(BaseSettings):
    """JWT配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="JWT_"
    )
    
    SECRET_KEY: str = Field(
        default="",
        description="JWT密钥（必须通过环境变量设置，在生产环境中使用强随机密钥）",
        min_length=32
    )
    ALGORITHM: str = Field(
        default="HS256",
        description="JWT算法"
    )
    ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(
        default=1440,
        description="JWT访问令牌过期时间(分钟)",
        ge=1,
        le=10080  # 最大7天
    )
    
    @model_validator(mode='after')
    def validate_jwt_settings(self) -> 'JWTSettings':
        """验证JWT配置"""
        if not self.SECRET_KEY:
            raise ValueError("JWT_SECRET_KEY不能为空，请在.env文件中设置")
        return self


class AppSettings(BaseSettings):
    """应用配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore"
    )
    
    DEBUG: bool = Field(
        default=True,
        description="调试模式"
    )
    HOST: str = Field(
        default="0.0.0.0",
        description="服务监听地址"
    )
    PORT: int = Field(
        default=8000,
        description="服务监听端口",
        ge=1,
        le=65535
    )
    LOG_LEVEL: str = Field(
        default="INFO",
        description="日志级别"
    )
    
    # HTTPS配置
    HTTPS_ENABLED: bool = Field(
        default=bool(os.getenv("HTTPS_ENABLE", "False")),
        description="是否启用HTTPS"
    )
    HTTPS_CERT_PATH: Optional[str] = Field(
        default=os.getenv("HTTPS_CERT_PATH", None),
        description="SSL证书文件路径"
    )
    HTTPS_KEY_PATH: Optional[str] = Field(
        default=os.getenv("HTTPS_KEY_PATH", None),
        description="SSL私钥文件路径"
    )
    
    @model_validator(mode='after')
    def validate_app_settings(self) -> 'AppSettings':
        """验证应用配置"""
        valid_log_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
        if self.LOG_LEVEL not in valid_log_levels:
            raise ValueError(f"LOG_LEVEL必须是以下值之一: {valid_log_levels}")
        
        # 如果启用了HTTPS，必须提供证书和私钥路径
        if self.HTTPS_ENABLED:
            if not self.HTTPS_CERT_PATH:
                raise ValueError("启用HTTPS时必须提供证书文件路径")
            if not self.HTTPS_KEY_PATH:
                raise ValueError("启用HTTPS时必须提供私钥文件路径")
            if not os.path.exists(self.HTTPS_CERT_PATH):
                raise ValueError(f"证书文件不存在: {self.HTTPS_CERT_PATH}")
            if not os.path.exists(self.HTTPS_KEY_PATH):
                raise ValueError(f"私钥文件不存在: {self.HTTPS_KEY_PATH}")
        return self


class CORSSettings(BaseSettings):
    """CORS配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="CORS_"
    )
    
    ORIGINS: List[str] = Field(
        default=["http://localhost:3000", "http://127.0.0.1:3000"],
        description="CORS允许的源"
    )
    
    @field_validator("ORIGINS", mode="before")
    @classmethod
    def parse_cors_origins(cls, v):
        """解析CORS origins配置"""
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",")]
        return v
    
    @model_validator(mode='after')
    def validate_cors_settings(self) -> 'CORSSettings':
        """验证CORS配置"""
        if not self.ORIGINS:
            raise ValueError("CORS_ORIGINS不能为空")
        return self


class MCPSettings(BaseSettings):
    """MCP配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="MCP_"
    )
    
    ENABLED: bool = Field(
        default=True,
        description="是否启用MCP功能"
    )
    SERVERS: List[str] = Field(
        default=[],
        description="MCP服务器列表"
    )
    CONFIG_SOURCE: str = Field(
        default="environment",
        description="MCP配置来源: environment, file, database, remote"
    )
    CONFIG_FILE_PATH: Optional[str] = Field(
        default="configs/mcp_config.json",
        description="MCP配置文件路径"
    )
    CONFIG_DATABASE_TABLE: Optional[str] = Field(
        default="mcp_configs",
        description="MCP配置数据库表名"
    )
    CONFIG_REMOTE_URL: Optional[str] = Field(
        default=None,
        description="MCP远程配置URL"
    )
    CONFIG_UPDATE_INTERVAL: int = Field(
        default=300,
        description="配置更新检查间隔(秒)",
        ge=10,
        le=3600
    )
    ENABLE_CONFIG_VERSIONING: bool = Field(
        default=True,
        description="是否启用配置版本管理"
    )
    MAX_CONFIG_VERSIONS: int = Field(
        default=10,
        description="最大配置版本数",
        ge=1,
        le=100
    )
    
    @field_validator('SERVERS', mode='before')
    @classmethod
    def validate_mcp_servers(cls, v) -> List[str]:
        """验证MCP服务器列表"""
        if isinstance(v, str):
            return [server.strip() for server in v.split(',') if server.strip()]
        return v


class EmailSettings(BaseSettings):
    """邮件配置类（功能已禁用，但代码中会检查这些变量）"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="SMTP_"
    )
    
    SERVER: Optional[str] = Field(
        default=None,
        description="SMTP服务器地址（功能已禁用）"
    )
    PORT: Optional[int] = Field(
        default=587,
        description="SMTP服务器端口（功能已禁用）",
        ge=1,
        le=65535
    )
    USERNAME: Optional[str] = Field(
        default=None,
        description="SMTP用户名（功能已禁用）"
    )
    PASSWORD: Optional[str] = Field(
        default=None,
        description="SMTP密码（功能已禁用）"
    )
    
    # EMAIL_FROM在环境变量中没有SMTP_前缀
    EMAIL_FROM: Optional[str] = Field(
        default=None,
        description="发件人邮箱（功能已禁用）"
    )


class SMSSettings(BaseSettings):
    """短信配置类（功能已禁用，但代码中会检查这些变量）"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore"
    )
    
    TWILIO_ACCOUNT_SID: Optional[str] = Field(
        default=None,
        description="Twilio账户SID（功能已禁用）"
    )
    TWILIO_AUTH_TOKEN: Optional[str] = Field(
        default=None,
        description="Twilio认证令牌（功能已禁用）"
    )


class CacheSettings(BaseSettings):
    """缓存配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="CACHE_"
    )
    
    DEFAULT_TTL: int = Field(
        default=3600,
        description="缓存默认生存时间(秒)",
        ge=1,
        le=86400  # 最大24小时
    )
    DIR: str = Field(
        default="data/cache",
        description="缓存文件存储目录"
    )
    
    @model_validator(mode='after')
    def validate_cache_settings(self) -> 'CacheSettings':
        """验证缓存配置"""
        if not self.DIR:
            raise ValueError("缓存目录不能为空")
        return self


class RedisSettings(BaseSettings):
    """Redis配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="REDIS_"
    )
    
    HOST: str = Field(
        default="localhost",
        description="Redis服务器地址"
    )
    PORT: int = Field(
        default=6379,
        description="Redis服务器端口",
        ge=1,
        le=65535
    )
    DB: int = Field(
        default=0,
        description="Redis数据库编号",
        ge=0,
        le=15
    )
    PASSWORD: Optional[str] = Field(
        default=None,
        description="Redis密码"
    )
    SHARDS: Optional[List[Dict[str, Any]]] = Field(
        default=None,
        description="Redis分片配置列表"
    )
    
    @field_validator("SHARDS", mode="before")
    @classmethod
    def parse_redis_shards(cls, v):
        """解析Redis分片配置"""
        if isinstance(v, str):
            try:
                import json
                return json.loads(v)
            except Exception:
                return None
        return v
    
    @model_validator(mode='after')
    def validate_redis_settings(self) -> 'RedisSettings':
        """验证Redis配置"""
        return self


class MonitoringSettings(BaseSettings):
    """监控配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="MONITORING_"
    )
    
    ENABLE_METRICS: bool = Field(
        default=True,
        description="是否启用指标监控"
    )
    METRICS_PORT: int = Field(
        default=8001,
        description="指标暴露端口（如果与主应用端口不同）",
        ge=1,
        le=65535
    )
    COLLECT_INTERVAL: int = Field(
        default=30,
        description="指标收集间隔（秒）",
        ge=1,
        le=300
    )
    ENABLE_BUSINESS_METRICS: bool = Field(
        default=True,
        description="是否启用业务指标收集"
    )
    ENABLE_DB_METRICS: bool = Field(
        default=True,
        description="是否启用数据库性能指标"
    )
    ENABLE_CACHE_METRICS: bool = Field(
        default=True,
        description="是否启用缓存性能指标"
    )
    ENABLE_EXTERNAL_METRICS: bool = Field(
        default=True,
        description="是否启用外部服务指标"
    )
    ENABLE_MCP_METRICS: bool = Field(
        default=True,
        description="是否启用MCP服务指标"
    )
    ENABLE_MCP_CALL_TRACING: bool = Field(
        default=True,
        description="是否启用MCP服务调用链追踪"
    )
    ENABLE_MCP_PLUGIN_ANALYTICS: bool = Field(
        default=True,
        description="是否启用MCP插件使用统计分析"
    )
    
    @model_validator(mode='after')
    def validate_monitoring_settings(self) -> 'MonitoringSettings':
        """验证监控配置"""
        if self.METRICS_PORT == 8000:  # 与主应用端口冲突
            raise ValueError("监控端口不能与主应用端口相同")
        return self


class MultimodalSettings(BaseSettings):
    """多模态处理配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="MULTIMODAL_"
    )
    
    ENABLED: bool = Field(
        default=True,
        description="是否启用多模态处理功能"
    )
    IMAGE_PROCESSING: bool = Field(
        default=True,
        description="是否启用图像处理功能"
    )
    TABLE_PROCESSING: bool = Field(
        default=True,
        description="是否启用表格处理功能"
    )
    MAX_IMAGES_PER_SEARCH: int = Field(
        default=10,
        description="每次搜索最多提取的图像数量",
        ge=0,
        le=50
    )
    MAX_TABLES_PER_SEARCH: int = Field(
        default=5,
        description="每次搜索最多提取的表格数量",
        ge=0,
        le=20
    )
    # 新增多模态处理配置
    CHART_PROCESSING: bool = Field(
        default=True,
        description="是否启用图表处理功能"
    )
    VIDEO_PROCESSING: bool = Field(
        default=True,
        description="是否启用视频处理功能"
    )
    DOCUMENT_OCR_PROCESSING: bool = Field(
        default=True,
        description="是否启用文档OCR处理功能"
    )
    SPEAKER_DIARIZATION: bool = Field(
        default=True,
        description="是否启用说话人分离功能"
    )
    SPEECH_TRANSLATION: bool = Field(
        default=True,
        description="是否启用语音翻译功能"
    )
    MAX_CHARTS_PER_SEARCH: int = Field(
        default=3,
        description="每次搜索最多提取的图表数量",
        ge=0,
        le=10
    )
    MAX_VIDEOS_PER_SEARCH: int = Field(
        default=2,
        description="每次搜索最多提取的视频数量",
        ge=0,
        le=5
    )
    MAX_DOCUMENT_IMAGES_PER_SEARCH: int = Field(
        default=3,
        description="每次搜索最多处理的文档图像数量",
        ge=0,
        le=10
    )


class WorkflowSettings(BaseSettings):
    """工作流配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="WORKFLOW_"
    )
    
    # 添加类型注解以解决Pydantic错误
    MAX_ITERATION_LIMIT: int = Field(
        default=2,
        description="工作流最大迭代次数限制",
        ge=1,
        le=100
    )
    
    # 阶段特定迭代策略配置
    PHASE_SPECIFIC_STRATEGIES: Dict[str, Dict[str, Any]] = Field(
        default={
            "requirements": {
                "focus_metrics": ["completeness", "clarity"],
                "improvement_threshold": 0.1,
                "max_iterations": 8
            },
            "design": {
                "focus_metrics": ["innovation", "usability"], 
                "improvement_threshold": 0.15,
                "max_iterations": 6
            },
            "development": {
                "focus_metrics": ["code_quality", "modularity"],
                "improvement_threshold": 0.2,
                "max_iterations": 12
            },
            "testing": {
                "focus_metrics": ["coverage", "pass_rate"],
                "improvement_threshold": 0.25,
                "max_iterations": 10
            }
        },
        description="阶段特定的迭代策略配置"
    )


class Settings(BaseSettings):
    """主配置类，聚合所有子配置"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore"
    )
    
    # 数据库配置
    DATABASE_URL: str = "sqlite:///./test.db"
    DATABASE_POOL_SIZE: int = 10
    DATABASE_MAX_OVERFLOW: int = 20
    DATABASE_POOL_TIMEOUT: int = 30
    DATABASE_POOL_RECYCLE: int = 3600
    DATABASE_ECHO: bool = False
    
    # 加密配置
    ENCRYPTION_SECRET_KEY: str = "your-super-secret-encryption-key-change-in-production"
    JWT_SECRET_KEY: str = "your-super-secret-jwt-key-change-this-in-production"
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440
    
    # Redis配置（用于分布式速率限制）
    REDIS_URL: Optional[str] = None
    
    # CORS配置
    CORS_ORIGINS: List[str] = Field(
        default=["http://localhost:3000", "http://127.0.0.1:3000"],
        description="CORS允许的源"
    )
    
    # MCP配置
    MCP_ENABLED: bool = Field(
        default=True,
        description="是否启用MCP功能"
    )
    MCP_SERVERS: List[str] = Field(
        default=[],
        description="MCP服务器列表"
    )
    MCP_SERVER_CONFIGS: Dict[str, Dict[str, Any]] = {}
    MCP_CONFIG_SOURCE: str = Field(
        default="environment",
        description="MCP配置来源: environment, file, database, remote"
    )
    MCP_CONFIG_FILE_PATH: Optional[str] = Field(
        default="configs/mcp_config.json",
        description="MCP配置文件路径"
    )
    MCP_CONFIG_DATABASE_TABLE: Optional[str] = Field(
        default="mcp_configs",
        description="MCP配置数据库表名"
    )
    MCP_CONFIG_REMOTE_URL: Optional[str] = Field(
        default=None,
        description="MCP远程配置URL"
    )
    MCP_CONFIG_UPDATE_INTERVAL: int = Field(
        default=300,
        description="配置更新检查间隔(秒)",
        ge=10,
        le=3600
    )
    MCP_ENABLE_CONFIG_VERSIONING: bool = Field(
        default=True,
        description="是否启用配置版本管理"
    )
    MCP_MAX_CONFIG_VERSIONS: int = Field(
        default=10,
        description="最大配置版本数",
        ge=1,
        le=100
    )
    
    # 邮件配置
    SMTP_SERVER: Optional[str] = Field(
        default=None,
        description="SMTP服务器地址（功能已禁用）"
    )
    SMTP_PORT: Optional[int] = Field(
        default=587,
        description="SMTP服务器端口（功能已禁用）",
        ge=1,
        le=65535
    )
    SMTP_USERNAME: Optional[str] = Field(
        default=None,
        description="SMTP用户名（功能已禁用）"
    )
    SMTP_PASSWORD: Optional[str] = Field(
        default=None,
        description="SMTP密码（功能已禁用）"
    )
    EMAIL_FROM: Optional[str] = Field(
        default=None,
        description="发件人邮箱（功能已禁用）"
    )
    
    # 短信配置
    TWILIO_ACCOUNT_SID: Optional[str] = Field(
        default=None,
        description="Twilio账户SID（功能已禁用）"
    )
    TWILIO_AUTH_TOKEN: Optional[str] = Field(
        default=None,
        description="Twilio认证令牌（功能已禁用）"
    )
    
    # 缓存配置
    CACHE_DEFAULT_TTL: int = Field(
        default=3600,
        description="缓存默认生存时间(秒)",
        ge=1,
        le=86400  # 最大24小时
    )
    CACHE_DIR: str = Field(
        default="data/cache",
        description="缓存文件存储目录"
    )
    
    # 监控配置
    ENABLE_METRICS: bool = Field(
        default=True,
        description="是否启用指标监控"
    )
    MONITORING_METRICS_PORT: int = Field(
        default=8001,
        description="指标暴露端口（如果与主应用端口不同）",
        ge=1,
        le=65535
    )
    MONITORING_COLLECT_INTERVAL: int = Field(
        default=30,
        description="指标收集间隔（秒）",
        ge=1,
        le=300
    )
    MONITORING_ENABLE_BUSINESS_METRICS: bool = Field(
        default=True,
        description="是否启用业务指标收集"
    )
    MONITORING_ENABLE_DB_METRICS: bool = Field(
        default=True,
        description="是否启用数据库性能指标"
    )
    MONITORING_ENABLE_CACHE_METRICS: bool = Field(
        default=True,
        description="是否启用缓存性能指标"
    )
    MONITORING_ENABLE_EXTERNAL_METRICS: bool = Field(
        default=True,
        description="是否启用外部服务指标"
    )
    MONITORING_ENABLE_MCP_METRICS: bool = Field(
        default=True,
        description="是否启用MCP服务指标"
    )
    MONITORING_ENABLE_MCP_CALL_TRACING: bool = Field(
        default=True,
        description="是否启用MCP服务调用链追踪"
    )
    MONITORING_ENABLE_MCP_PLUGIN_ANALYTICS: bool = Field(
        default=True,
        description="是否启用MCP插件使用统计分析"
    )
    
    # 多模态配置
    MULTIMODAL_ENABLED: bool = Field(
        default=True,
        description="是否启用多模态处理功能"
    )
    MULTIMODAL_IMAGE_PROCESSING: bool = Field(
        default=True,
        description="是否启用图像处理功能"
    )
    MULTIMODAL_TABLE_PROCESSING: bool = Field(
        default=True,
        description="是否启用表格处理功能"
    )
    MAX_IMAGES_PER_SEARCH: int = Field(
        default=10,
        description="每次搜索最多提取的图像数量",
        ge=0,
        le=50
    )
    MAX_TABLES_PER_SEARCH: int = Field(
        default=5,
        description="每次搜索最多提取的表格数量",
        ge=0,
        le=20
    )
    # 新增多模态处理配置
    MULTIMODAL_CHART_PROCESSING: bool = Field(
        default=True,
        description="是否启用图表处理功能"
    )
    MULTIMODAL_VIDEO_PROCESSING: bool = Field(
        default=True,
        description="是否启用视频处理功能"
    )
    MULTIMODAL_DOCUMENT_OCR_PROCESSING: bool = Field(
        default=True,
        description="是否启用文档OCR处理功能"
    )
    MULTIMODAL_SPEAKER_DIARIZATION: bool = Field(
        default=True,
        description="是否启用说话人分离功能"
    )
    MULTIMODAL_SPEECH_TRANSLATION: bool = Field(
        default=True,
        description="是否启用语音翻译功能"
    )
    MAX_CHARTS_PER_SEARCH: int = Field(
        default=3,
        description="每次搜索最多提取的图表数量",
        ge=0,
        le=10
    )
    MAX_VIDEOS_PER_SEARCH: int = Field(
        default=2,
        description="每次搜索最多提取的视频数量",
        ge=0,
        le=5
    )
    MAX_DOCUMENT_IMAGES_PER_SEARCH: int = Field(
        default=3,
        description="每次搜索最多处理的文档图像数量",
        ge=0,
        le=10
    )
    
    # 工作流配置
    WORKFLOW_MAX_ITERATION_LIMIT: int = Field(
        default=2,
        description="工作流最大迭代次数限制",
        ge=1,
        le=100
    )
    WORKFLOW_PHASE_SPECIFIC_STRATEGIES: Dict[str, Dict[str, Any]] = Field(
        default={
            "requirements": {
                "focus_metrics": ["completeness", "clarity"],
                "improvement_threshold": 0.1,
                "max_iterations": 8
            },
            "design": {
                "focus_metrics": ["innovation", "usability"], 
                "improvement_threshold": 0.15,
                "max_iterations": 6
            },
            "development": {
                "focus_metrics": ["code_quality", "modularity"],
                "improvement_threshold": 0.2,
                "max_iterations": 12
            },
            "testing": {
                "focus_metrics": ["coverage", "pass_rate"],
                "improvement_threshold": 0.25,
                "max_iterations": 10
            }
        },
        description="阶段特定的迭代策略配置"
    )
    
    # 知识图谱配置
    KG_NEO4J_URI: Optional[str] = Field(
        default=None,
        description="Neo4j数据库URI"
    )
    KG_NEO4J_USER: Optional[str] = Field(
        default=None,
        description="Neo4j数据库用户名"
    )
    KG_NEO4J_PASSWORD: Optional[str] = Field(
        default=None,
        description="Neo4j数据库密码"
    )
    
    # 类型注解，让静态分析工具能够识别动态设置的属性
    database: DatabaseSettings
    jwt: JWTSettings
    app: AppSettings
    cors: CORSSettings
    mcp: MCPSettings
    email: EmailSettings
    sms: SMSSettings
    cache: CacheSettings
    redis: RedisSettings
    monitoring: MonitoringSettings
    multimodal: MultimodalSettings
    workflow: WorkflowSettings

    # 兼容性属性
    DATABASE_URL: str
    DATABASE_POOL_SIZE: int
    DATABASE_MAX_OVERFLOW: int
    DATABASE_POOL_TIMEOUT: int
    DATABASE_POOL_RECYCLE: int
    DATABASE_ECHO: bool

    ENCRYPTION_SECRET_KEY: str
    JWT_SECRET_KEY: str
    JWT_ALGORITHM: str
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int

    DEBUG: bool
    HOST: str
    PORT: int
    LOG_LEVEL: str
    HTTPS_ENABLED: bool
    HTTPS_CERT_PATH: Optional[str]
    HTTPS_KEY_PATH: Optional[str]

    CORS_ORIGINS: List[str]

    MCP_ENABLED: bool
    MCP_SERVERS: List[str]
    MCP_SERVER_CONFIGS: Dict[str, Dict[str, Any]]

    SMTP_SERVER: Optional[str]
    SMTP_PORT: Optional[int]
    SMTP_USERNAME: Optional[str]
    SMTP_PASSWORD: Optional[str]
    EMAIL_FROM: Optional[str]

    TWILIO_ACCOUNT_SID: Optional[str]
    TWILIO_AUTH_TOKEN: Optional[str]

    CACHE_DEFAULT_TTL: int
    CACHE_DIR: str

    REDIS_HOST: str
    REDIS_PORT: int
    REDIS_DB: int
    REDIS_PASSWORD: Optional[str]
    REDIS_SHARDS: Optional[List[Dict[str, Any]]]

    ENABLE_METRICS: bool
    MONITORING_METRICS_PORT: int
    MONITORING_COLLECT_INTERVAL: int
    MONITORING_ENABLE_BUSINESS_METRICS: bool
    MONITORING_ENABLE_DB_METRICS: bool
    MONITORING_ENABLE_CACHE_METRICS: bool
    MONITORING_ENABLE_EXTERNAL_METRICS: bool
    MONITORING_ENABLE_MCP_METRICS: bool
    MONITORING_ENABLE_MCP_CALL_TRACING: bool
    MONITORING_ENABLE_MCP_PLUGIN_ANALYTICS: bool

    MULTIMODAL_ENABLED: bool
    MULTIMODAL_IMAGE_PROCESSING: bool
    MULTIMODAL_TABLE_PROCESSING: bool
    MAX_IMAGES_PER_SEARCH: int
    MAX_TABLES_PER_SEARCH: int

    WORKFLOW_MAX_ITERATION_LIMIT: int
    WORKFLOW_PHASE_SPECIFIC_STRATEGIES: Dict[str, Dict[str, Any]]
    
    # MCP配置版本管理属性
    MCP_CONFIG_VERSIONS: Dict[str, List[Dict[str, Any]]] = {}
    MCP_CONFIG_CHECKSUMS: Dict[str, str] = {}
    
    # 知识图谱配置属性
    KG_NEO4J_URI: Optional[str]
    KG_NEO4J_USER: Optional[str]
    KG_NEO4J_PASSWORD: Optional[str]
    
    def __init__(self):
        # 使用object.__setattr__来避免pydantic的字段验证
        object.__setattr__(self, 'database', DatabaseSettings())
        object.__setattr__(self, 'jwt', JWTSettings())
        object.__setattr__(self, 'app', AppSettings())
        object.__setattr__(self, 'cors', CORSSettings())
        object.__setattr__(self, 'mcp', MCPSettings())
        object.__setattr__(self, 'email', EmailSettings())
        object.__setattr__(self, 'sms', SMSSettings())
        object.__setattr__(self, 'cache', CacheSettings())
        object.__setattr__(self, 'redis', RedisSettings())  # 添加Redis配置
        object.__setattr__(self, 'monitoring', MonitoringSettings())
        object.__setattr__(self, 'multimodal', MultimodalSettings())
        object.__setattr__(self, 'workflow', WorkflowSettings())
        
        # 保持与原来配置的兼容性
        self._init_compatibility_properties()
        self._init_mcp_configs()
    
    def _init_compatibility_properties(self):
        """初始化兼容性属性，保持与旧代码的兼容"""
        # 数据库相关
        object.__setattr__(self, 'DATABASE_URL', self.database.URL)
        
        # 添加MCP配置版本相关属性到兼容性属性
        object.__setattr__(self, 'MCP_CONFIG_VERSIONS', {})
        object.__setattr__(self, 'MCP_CONFIG_CHECKSUMS', {})
        
        # MCP配置源相关
        object.__setattr__(self, 'MCP_CONFIG_SOURCE', self.mcp.CONFIG_SOURCE)
        object.__setattr__(self, 'MCP_CONFIG_FILE_PATH', self.mcp.CONFIG_FILE_PATH)
        object.__setattr__(self, 'MCP_CONFIG_DATABASE_TABLE', self.mcp.CONFIG_DATABASE_TABLE)
        object.__setattr__(self, 'MCP_CONFIG_REMOTE_URL', self.mcp.CONFIG_REMOTE_URL)
        object.__setattr__(self, 'MCP_CONFIG_UPDATE_INTERVAL', self.mcp.CONFIG_UPDATE_INTERVAL)
        object.__setattr__(self, 'MCP_ENABLE_CONFIG_VERSIONING', self.mcp.ENABLE_CONFIG_VERSIONING)
        object.__setattr__(self, 'MCP_MAX_CONFIG_VERSIONS', self.mcp.MAX_CONFIG_VERSIONS)
        object.__setattr__(self, 'DATABASE_POOL_SIZE', self.database.POOL_SIZE)
        object.__setattr__(self, 'DATABASE_MAX_OVERFLOW', self.database.MAX_OVERFLOW)
        object.__setattr__(self, 'DATABASE_POOL_TIMEOUT', self.database.POOL_TIMEOUT)
        object.__setattr__(self, 'DATABASE_POOL_RECYCLE', self.database.POOL_RECYCLE)
        object.__setattr__(self, 'DATABASE_ECHO', self.database.ECHO)
            
        # JWT相关
        object.__setattr__(self, 'JWT_SECRET_KEY', self.jwt.SECRET_KEY)
        object.__setattr__(self, 'JWT_ALGORITHM', self.jwt.ALGORITHM)
        object.__setattr__(self, 'JWT_ACCESS_TOKEN_EXPIRE_MINUTES', self.jwt.ACCESS_TOKEN_EXPIRE_MINUTES)
            
        # 应用相关
        object.__setattr__(self, 'DEBUG', self.app.DEBUG)
        object.__setattr__(self, 'HOST', self.app.HOST)
        object.__setattr__(self, 'PORT', self.app.PORT)
        object.__setattr__(self, 'LOG_LEVEL', self.app.LOG_LEVEL)
        object.__setattr__(self, 'HTTPS_ENABLED', self.app.HTTPS_ENABLED)
        object.__setattr__(self, 'HTTPS_CERT_PATH', self.app.HTTPS_CERT_PATH)
        object.__setattr__(self, 'HTTPS_KEY_PATH', self.app.HTTPS_KEY_PATH)
        
        # CORS相关
        object.__setattr__(self, 'CORS_ORIGINS', self.cors.ORIGINS)
        
        # MCP相关
        object.__setattr__(self, 'MCP_ENABLED', self.mcp.ENABLED)
        object.__setattr__(self, 'MCP_SERVERS', self.mcp.SERVERS)
        object.__setattr__(self, 'MCP_SERVER_CONFIGS', {})
        object.__setattr__(self, 'MCP_CONFIG_VERSIONS', {})
        object.__setattr__(self, 'MCP_CONFIG_CHECKSUMS', {})
        
        # 邮件相关
        object.__setattr__(self, 'SMTP_SERVER', self.email.SERVER)
        object.__setattr__(self, 'SMTP_PORT', self.email.PORT)
        object.__setattr__(self, 'SMTP_USERNAME', self.email.USERNAME)
        object.__setattr__(self, 'SMTP_PASSWORD', self.email.PASSWORD)
        object.__setattr__(self, 'EMAIL_FROM', self.email.EMAIL_FROM)
        
        # 短信相关
        object.__setattr__(self, 'TWILIO_ACCOUNT_SID', self.sms.TWILIO_ACCOUNT_SID)
        object.__setattr__(self, 'TWILIO_AUTH_TOKEN', self.sms.TWILIO_AUTH_TOKEN)
        
        # 缓存相关
        object.__setattr__(self, 'CACHE_DEFAULT_TTL', self.cache.DEFAULT_TTL)
        object.__setattr__(self, 'CACHE_DIR', self.cache.DIR)
        
        # Redis相关
        object.__setattr__(self, 'REDIS_HOST', self.redis.HOST)
        object.__setattr__(self, 'REDIS_PORT', self.redis.PORT)
        object.__setattr__(self, 'REDIS_DB', self.redis.DB)
        object.__setattr__(self, 'REDIS_PASSWORD', self.redis.PASSWORD)
        object.__setattr__(self, 'REDIS_SHARDS', self.redis.SHARDS)
        
        # 监控相关
        object.__setattr__(self, 'ENABLE_METRICS', self.monitoring.ENABLE_METRICS)
        object.__setattr__(self, 'MONITORING_METRICS_PORT', self.monitoring.METRICS_PORT)
        object.__setattr__(self, 'MONITORING_COLLECT_INTERVAL', self.monitoring.COLLECT_INTERVAL)
        object.__setattr__(self, 'MONITORING_ENABLE_BUSINESS_METRICS', self.monitoring.ENABLE_BUSINESS_METRICS)
        object.__setattr__(self, 'MONITORING_ENABLE_DB_METRICS', self.monitoring.ENABLE_DB_METRICS)
        object.__setattr__(self, 'MONITORING_ENABLE_CACHE_METRICS', self.monitoring.ENABLE_CACHE_METRICS)
        object.__setattr__(self, 'MONITORING_ENABLE_EXTERNAL_METRICS', self.monitoring.ENABLE_EXTERNAL_METRICS)
        object.__setattr__(self, 'MONITORING_ENABLE_MCP_METRICS', self.monitoring.ENABLE_MCP_METRICS)
        object.__setattr__(self, 'MONITORING_ENABLE_MCP_CALL_TRACING', self.monitoring.ENABLE_MCP_CALL_TRACING)
        object.__setattr__(self, 'MONITORING_ENABLE_MCP_PLUGIN_ANALYTICS', self.monitoring.ENABLE_MCP_PLUGIN_ANALYTICS)
        
        # 多模态相关
        object.__setattr__(self, 'MULTIMODAL_ENABLED', self.multimodal.ENABLED)
        object.__setattr__(self, 'MULTIMODAL_IMAGE_PROCESSING', self.multimodal.IMAGE_PROCESSING)
        object.__setattr__(self, 'MULTIMODAL_TABLE_PROCESSING', self.multimodal.TABLE_PROCESSING)
        object.__setattr__(self, 'MAX_IMAGES_PER_SEARCH', self.multimodal.MAX_IMAGES_PER_SEARCH)
        object.__setattr__(self, 'MAX_TABLES_PER_SEARCH', self.multimodal.MAX_TABLES_PER_SEARCH)
        
        # 工作流相关
        object.__setattr__(self, 'WORKFLOW_MAX_ITERATION_LIMIT', self.workflow.MAX_ITERATION_LIMIT)
        object.__setattr__(self, 'WORKFLOW_PHASE_SPECIFIC_STRATEGIES', self.workflow.PHASE_SPECIFIC_STRATEGIES)
    
    def _init_mcp_configs(self):
        """初始化MCP服务器配置"""
        # 初始化MCP配置，避免循环引用
        if not hasattr(self, 'MCP_SERVER_CONFIGS') or not self.MCP_SERVER_CONFIGS:
            object.__setattr__(self, 'MCP_SERVER_CONFIGS', {})
        
        # 为每个配置的服务器添加默认配置
        if hasattr(self, 'MCP_SERVERS'):
            for server in self.MCP_SERVERS:
                server = server.strip()
                if server and server not in self.MCP_SERVER_CONFIGS:
                    # 每个服务器的独立启用状态，默认为全局启用状态
                    enabled_key = f"MCP_{server.upper().replace('-', '_')}_ENABLED"
                    # 从环境变量获取特定服务器的启用状态，如果未设置则使用全局设置
                    enabled_from_env = os.getenv(enabled_key)
                    enabled = self.MCP_ENABLED
                    if enabled_from_env is not None:
                        enabled = enabled_from_env.lower() == "true"
                    
                    self.MCP_SERVER_CONFIGS[server] = {
                        'enabled': enabled,
                        'url': os.getenv(f"MCP_{server.upper().replace('-', '_')}_URL", ""),
                        'api_key': os.getenv(f"MCP_{server.upper().replace('-', '_')}_API_KEY", ""),
                        'timeout': int(os.getenv(f"MCP_{server.upper().replace('-', '_')}_TIMEOUT", "30")),
                        'retries': int(os.getenv(f"MCP_{server.upper().replace('-', '_')}_RETRIES", "3"))
                    }
    
    def _load_mcp_configs_from_source(self):
        """从配置源加载MCP配置"""
        source = self.mcp.CONFIG_SOURCE
        try:
            if source == "environment":
                self._init_mcp_configs()
            elif source == "file":
                self._load_mcp_configs_from_file()
            elif source == "database":
                self._load_mcp_configs_from_database()
            elif source == "remote":
                self._load_mcp_configs_from_remote()
            else:
                logger.warning(f"未知的MCP配置源: {source}，使用默认环境变量配置")
                self._init_mcp_configs()
                
            # 记录配置版本
            self._record_config_version(source)
        except Exception as e:
            logger.error(f"从 {source} 加载MCP配置失败: {e}")
            # 回退到环境变量配置
            self._init_mcp_configs()
    
    def _load_mcp_configs_from_file(self):
        """从文件加载MCP配置"""
        import json
        import yaml
        import os
        
        config_file_path = self.mcp.CONFIG_FILE_PATH
        if not config_file_path or not os.path.exists(config_file_path):
            logger.warning(f"MCP配置文件不存在: {config_file_path}")
            return
            
        try:
            with open(config_file_path, 'r', encoding='utf-8') as f:
                if config_file_path.endswith('.json'):
                    config_data = json.load(f)
                elif config_file_path.endswith(('.yml', '.yaml')):
                    config_data = yaml.safe_load(f)
                else:
                    logger.warning(f"不支持的配置文件格式: {config_file_path}")
                    return
                    
            # 更新配置
            if 'servers' in config_data:
                object.__setattr__(self, 'MCP_SERVERS', config_data['servers'])
            
            if 'server_configs' in config_data:
                object.__setattr__(self, 'MCP_SERVER_CONFIGS', config_data['server_configs'])
                
            logger.info(f"从文件加载MCP配置成功: {config_file_path}")
        except Exception as e:
            logger.error(f"从文件加载MCP配置失败: {e}")
            raise
    
    def _load_mcp_configs_from_database(self):
        """从数据库加载MCP配置（占位符实现）"""
        logger.info("从数据库加载MCP配置（占位符实现）")
        # 实际实现需要根据数据库表结构来实现
    
    def _load_mcp_configs_from_remote(self):
        """从远程URL加载MCP配置（占位符实现）"""
        logger.info("从远程URL加载MCP配置（占位符实现）")
        # 实际实现需要使用HTTP客户端获取远程配置
    
    def _record_config_version(self, source: str):
        """记录配置版本"""
        if not self.mcp.ENABLE_CONFIG_VERSIONING:
            return
            
        import time
        import hashlib
        import json
        
        # 计算配置校验和
        config_data = {
            'servers': getattr(self, 'MCP_SERVERS', []),
            'server_configs': getattr(self, 'MCP_SERVER_CONFIGS', {})
        }
        checksum = hashlib.md5(json.dumps(config_data, sort_keys=True).encode()).hexdigest()
        
        # 创建版本记录
        version_record = {
            "version": len(self.MCP_CONFIG_VERSIONS.get(source, [])) + 1,
            "source": source,
            "timestamp": time.time(),
            "checksum": checksum,
            "config": config_data
        }
        
        # 更新版本历史
        if source not in self.MCP_CONFIG_VERSIONS:
            self.MCP_CONFIG_VERSIONS[source] = []
        
        self.MCP_CONFIG_VERSIONS[source].append(version_record)
        
        # 限制版本数量
        if len(self.MCP_CONFIG_VERSIONS[source]) > self.mcp.MAX_CONFIG_VERSIONS:
            self.MCP_CONFIG_VERSIONS[source] = self.MCP_CONFIG_VERSIONS[source][-self.mcp.MAX_CONFIG_VERSIONS:]
    
    def _calculate_config_checksum(self, config_data: Dict[str, Any]) -> str:
        """计算配置校验和"""
        return hashlib.md5(json.dumps(config_data, sort_keys=True).encode()).hexdigest()
    
    def reload_mcp_configs(self):
        """重新加载MCP配置（热更新）"""
        print("正在重新加载MCP配置...")
        old_checksum = self._calculate_config_checksum(self.MCP_SERVER_CONFIGS)
        self._load_mcp_configs_from_source()
        new_checksum = self._calculate_config_checksum(self.MCP_SERVER_CONFIGS)
        
        if old_checksum != new_checksum:
            print("MCP配置已更新")
            return True
        else:
            print("MCP配置无变化")
            return False
    
    def rollback_mcp_config(self, source: str, version: int) -> bool:
        """回滚MCP配置到指定版本"""
        if not self.mcp.ENABLE_CONFIG_VERSIONING:
            print("配置版本管理未启用")
            return False
        
        if source not in self.MCP_CONFIG_VERSIONS:
            print(f"配置源 {source} 不存在")
            return False
        
        versions = self.MCP_CONFIG_VERSIONS[source]
        target_version = None
        for v in versions:
            if v["version"] == version:
                target_version = v
                break
        
        if not target_version:
            print(f"版本 {version} 不存在")
            return False
        
        # 应用回滚的配置
        config_data = target_version["config"]
        if 'servers' in config_data:
            object.__setattr__(self, 'MCP_SERVERS', config_data['servers'])
        
        if 'server_configs' in config_data:
            object.__setattr__(self, 'MCP_SERVER_CONFIGS', config_data['server_configs'])
        
        print(f"已回滚到配置源 {source} 的版本 {version}")
        return True
    
    def get_config_versions(self, source: Optional[str] = None) -> Dict[str, List[Dict[str, Any]]]:
        """获取配置版本历史"""
        if not self.mcp.ENABLE_CONFIG_VERSIONING:
            return {}
        
        if source:
            return {source: self.MCP_CONFIG_VERSIONS.get(source, [])}
        return self.MCP_CONFIG_VERSIONS
    
    def init_mcp_configs(self):
        """初始化MCP服务器配置"""
        self._init_mcp_configs()
    
    def get_mcp_server_config(self, server_name: str) -> dict:
        """
        获取特定MCP服务器的配置
        
        Args:
            server_name: 服务器名称
            
        Returns:
            服务器配置字典
        """
        if not hasattr(self, 'MCP_SERVER_CONFIGS'):
            self.init_mcp_configs()
            
        return self.MCP_SERVER_CONFIGS.get(server_name, {})
    
    def is_mcp_server_enabled(self, server_name: str) -> bool:
        """
        检查MCP服务器是否启用
        
        Args:
            server_name: 服务器名称
            
        Returns:
            服务器是否启用
        """
        if not hasattr(self, 'MCP_SERVER_CONFIGS'):
            self.init_mcp_configs()
            
        server_config = self.MCP_SERVER_CONFIGS.get(server_name, {})
        return server_config.get('enabled', self.MCP_ENABLED)
    
    def update_mcp_server_config(self, server_name: str, config: dict):
        """
        更新MCP服务器配置
        
        Args:
            server_name: 服务器名称
            config: 配置字典
        """
        if not hasattr(self, 'MCP_SERVER_CONFIGS'):
            self.init_mcp_configs()
            
        if server_name not in self.MCP_SERVER_CONFIGS:
            self.MCP_SERVER_CONFIGS[server_name] = {
                'enabled': self.MCP_ENABLED,
                'url': "",
                'api_key': "",
                'timeout': 30,
                'retries': 3
            }
        
        self.MCP_SERVER_CONFIGS[server_name].update(config)

# 创建全局settings实例
settings = Settings()
